import { getDateDiff, orderBy } from 'xe-utils';
interface Invoice {
    startDate: string;
    endDate: string;
    propertyNumber?: string;
    propertyId?: string;
    roomNum?: string;
    roomId?: string;
}
const useInvoiceRemark = () => {
    function isContinuous(date1: string, date2: string): boolean {
        const diff: any = getDateDiff(date1, date2);
        return diff.done && diff.time > 60 * 60 * 24 * 1000;
    }

    function mergeContinuousDays(list: Invoice[], key: string): Invoice[] {
        const result = orderBy(list || [], [
            [item => item.startDate, 'asc'],
            [item => item.chargeItemId, 'asc'],
        ]).reduce((pre, cur) => {
            if (pre?.length > 0) {
                const roomKey = `${key}Id`;
                if (cur[roomKey] === pre[pre.length - 1][roomKey]) {
                    if (isContinuous(pre[pre.length - 1].endDate, cur.startDate)) {
                        return [...pre, cur];
                    } else {
                        pre[pre.length - 1].endDate = cur.endDate;
                        return pre;
                    }
                } else {
                    return [...pre, cur];
                }
            } else {
                return [cur];
            }
        }, []);

        return result.reduce(
            (pre, cur) => pre + `${[cur.startDate, cur.endDate].filter(Boolean).join('~')} ${cur.chargeItem} ${cur[key === 'room' ? 'roomNum' : 'propertyNumber'] || ''}\n`,
            '',
        );
    }

    return {
        mergeContinuousDays,
    };
};

export default useInvoiceRemark;
